// 自行车产品API路由
import express from 'express';
import BikeProductService from '../services/bike-product-service.js';
import { postgresPool } from '../../config/multi-database.js';

const router = express.Router();

// 获取产品列表
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 20, 
      category, 
      brand, 
      min_price, 
      max_price, 
      keyword,
      sort_by = 'created_at',
      sort_order = 'desc'
    } = req.query;
    
    const filters = {
      category_id: category,
      brand,
      min_price: min_price ? parseFloat(min_price) : undefined,
      max_price: max_price ? parseFloat(max_price) : undefined,
      keyword
    };
    
    // 清理空值
    Object.keys(filters).forEach(key => {
      if (filters[key] === undefined || filters[key] === '') {
        delete filters[key];
      }
    });
    
    const result = await BikeProductService.searchProducts({
      filters,
      page: parseInt(page),
      limit: parseInt(limit)
    }, req.user?.id);
    
    res.json({
      success: true,
      data: result
    });
    
  } catch (error) {
    console.error('获取产品列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取产品列表失败',
      error: error.message
    });
  }
});

// 获取产品详情
router.get('/:id', async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    
    if (isNaN(productId)) {
      return res.status(400).json({
        success: false,
        message: '产品ID格式错误'
      });
    }
    
    const productDetail = await BikeProductService.getProductDetail(
      productId, 
      req.user?.id
    );
    
    if (!productDetail) {
      return res.status(404).json({
        success: false,
        message: '产品不存在'
      });
    }
    
    res.json({
      success: true,
      data: productDetail
    });
    
  } catch (error) {
    console.error('获取产品详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取产品详情失败',
      error: error.message
    });
  }
});

// 获取产品评价
router.get('/:id/reviews', async (req, res) => {
  try {
    const productId = parseInt(req.params.id);
    const { page = 1, limit = 10, sort_by = 'created_at' } = req.query;
    
    if (isNaN(productId)) {
      return res.status(400).json({
        success: false,
        message: '产品ID格式错误'
      });
    }
    
    const reviews = await BikeProductService.getProductReviews(
      productId, 
      parseInt(page), 
      parseInt(limit), 
      sort_by
    );
    
    res.json({
      success: true,
      data: reviews
    });
    
  } catch (error) {
    console.error('获取产品评价失败:', error);
    res.status(500).json({
      success: false,
      message: '获取产品评价失败',
      error: error.message
    });
  }
});

// 添加产品评价（需要认证）
router.post('/:id/reviews', async (req, res) => {
  try {
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '请先登录'
      });
    }
    
    const productId = parseInt(req.params.id);
    const { rating, title, content, images = [], tags = [] } = req.body;
    
    if (isNaN(productId)) {
      return res.status(400).json({
        success: false,
        message: '产品ID格式错误'
      });
    }
    
    if (!rating || !title || !content) {
      return res.status(400).json({
        success: false,
        message: '请填写完整的评价信息'
      });
    }
    
    if (rating < 1 || rating > 5) {
      return res.status(400).json({
        success: false,
        message: '评分必须在1-5之间'
      });
    }
    
    const review = await BikeProductService.addProductReview({
      product_id: productId,
      user_id: req.user.id,
      rating: parseInt(rating),
      title,
      content,
      images,
      tags,
      verified_purchase: true // 简化处理，实际应该验证购买记录
    });
    
    res.json({
      success: true,
      message: '评价添加成功',
      data: review
    });
    
  } catch (error) {
    console.error('添加产品评价失败:', error);
    res.status(500).json({
      success: false,
      message: '添加产品评价失败',
      error: error.message
    });
  }
});

// 获取热门产品
router.get('/hot/list', async (req, res) => {
  try {
    const { limit = 10 } = req.query;
    
    const hotProducts = await BikeProductService.getProductRecommendations(
      req.user?.id, 
      parseInt(limit)
    );
    
    res.json({
      success: true,
      data: hotProducts
    });
    
  } catch (error) {
    console.error('获取热门产品失败:', error);
    res.status(500).json({
      success: false,
      message: '获取热门产品失败',
      error: error.message
    });
  }
});

// 搜索产品
router.get('/search/suggest', async (req, res) => {
  try {
    const { q, limit = 5 } = req.query;
    
    if (!q || q.trim().length === 0) {
      return res.json({
        success: true,
        data: []
      });
    }
    
    const client = await postgresPool.connect();
    
    try {
      const query = `
        SELECT id, name, model, brand
        FROM bike_products 
        WHERE status = 'active' 
          AND (name ILIKE $1 OR model ILIKE $1 OR brand ILIKE $1)
        LIMIT $2
      `;
      
      const result = await client.query(query, [`%${q}%`, parseInt(limit)]);
      
      res.json({
        success: true,
        data: result.rows
      });
      
    } finally {
      client.release();
    }
    
  } catch (error) {
    console.error('搜索建议失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索建议失败',
      error: error.message
    });
  }
});

// 获取产品分类
router.get('/categories/list', async (req, res) => {
  try {
    const client = await postgresPool.connect();
    
    try {
      const query = `
        SELECT id, name, description, parent_id, 
               (SELECT COUNT(*) FROM bike_products WHERE category_id = pc.id AND status = 'active') as product_count
        FROM product_categories pc
        WHERE status = 'active'
        ORDER BY parent_id NULLS FIRST, name
      `;
      
      const result = await client.query(query);
      
      // 构建分类树
      const categories = result.rows;
      const categoryMap = new Map();
      const rootCategories = [];
      
      categories.forEach(category => {
        categoryMap.set(category.id, { ...category, children: [] });
      });
      
      categories.forEach(category => {
        if (category.parent_id && categoryMap.has(category.parent_id)) {
          categoryMap.get(category.parent_id).children.push(categoryMap.get(category.id));
        } else {
          rootCategories.push(categoryMap.get(category.id));
        }
      });
      
      res.json({
        success: true,
        data: rootCategories
      });
      
    } finally {
      client.release();
    }
    
  } catch (error) {
    console.error('获取产品分类失败:', error);
    res.status(500).json({
      success: false,
      message: '获取产品分类失败',
      error: error.message
    });
  }
});

export default router;